﻿#include "stdafx.h"
#include "frmIM.h"
#include "AsyncHttpUtils.h"
using namespace rjksClient;
void frmIM::GetPush()
{
	while(true)
	{
		JObject^ jo= AsyncHttpUtils::GetResponse("im/push?targid="+this->targuinfo.uid);
		String^ ret=jo["msg"]->ToString();
		if(jo["err"]->ToString()=="1"){
			accum_error+=1;
		}else{
			accum_error=0;
			if(ret=="ok"){
				this->Invoke(gcnew JArraryParamDelegate(this,&frmIM::AddResponseWords),Utils::SafeWrapper(jo));
			}
		}
		if(Utils::GetTimeStamp()-last_msg_time>5*push_interval)
			push_interval+=2.1;//increase
		else if(Utils::GetTimeStamp()-last_msg_time<5)
			push_interval=1.5; //decrease
		push_interval+=accum_error*2;//error delay
		if(push_interval<1)
			push_interval=1;//MIN 1s
		else if(push_interval>10)
			push_interval=10;//MAX 10s
		System::Threading::Thread::Sleep(push_interval*1000);
	}
}

System::Void frmIM::btnSend_Click(System::Object^  sender, System::EventArgs^  e) {
	if(this->rtxtSend->Text!="")
	{
		this->panelFace->Visible=false;
		if(last_talk!=CHARA_SELF || Utils::GetTimeStamp()-last_msg_time>10){
			Append2Conversation(this->uinfo.uname,Color::Green,gcnew System::Drawing::Font("微软雅黑",13.0F,FontStyle::Regular));
			Append2Conversation(DateTime::Now.ToString("yy-MM-dd hh:mm"),Color::SlateGray,gcnew System::Drawing::Font("Consolas",8.0F,FontStyle::Regular));
		}
		Append2Conversation("· "+rtxtSend->Text);
		String^ _w=rtxtSend->Text;
		JObject^ jo=AsyncHttpUtils::GetResponse("im/talk","words="+Utils::Urlencode(rtxtSend->Text)+"&targid="+this->targuinfo.uid);
		if(jo["msg"]->ToString()!="ok")
			Append2Conversation("由于网络原因，\""+_w+"\"发送失败。",Color::White,Color::Gray,gcnew System::Drawing::Font("微软雅黑",7.0F,FontStyle::Regular));
		last_talk=CHARA_SELF;
		last_msg_time=Utils::GetTimeStamp();
		this->rtxtSend->Text="";
		this->rtxtSend->Focus();
	}
}
void frmIM::AddResponseWords(JArray^ ja)
{
	for each (JToken^ j in ja){
		if(last_talk!=CHARA_TARG || Utils::GetTimeStamp()-last_msg_time>10){
			Append2Conversation(this->targuinfo.uname,Color::Red,gcnew System::Drawing::Font("微软雅黑",13.0F,FontStyle::Regular));
			Append2Conversation(Utils::ParseTimeStamp(j["t"]->ToString()).ToString("yy-MM-dd hh:mm"),Color::Gray,gcnew System::Drawing::Font("Consolas",8.0F,FontStyle::Regular));
		}
		Append2Conversation("  "+Utils::Urldecode(j["w"]->ToString()));
		last_talk=CHARA_TARG;
		last_msg_time=Utils::GetTimeStamp();
	}
}

void frmIM::Append2Conversation(String^ input)
{
	Append2Conversation(input, Color::Black, rtxtConversation->Font);
}

void frmIM::Append2Conversation(String^ input, Color color)
{
		
}

void frmIM::Append2Conversation(String^ input, System::Drawing::Font^ font)
{
		
}
void frmIM::Append2Conversation(String^ input, Color color,System::Drawing::Font^ font){
	Append2Conversation(input,color,Color::Transparent,font);
}

void frmIM::Append2Conversation(String^ input, Color color, Color bkcolor,System::Drawing::Font^ font)
{
		this->rtxtConversation_lock->WaitOne();
		array<String^>^ splt={"!#"};
		array<String^>^ res=input->Split(splt,StringSplitOptions::RemoveEmptyEntries);
		_AppendText2Conversation(res[0],color,bkcolor,font,false);//first sector is pure text
		bool has_skip=false;
		System::Resources::ResourceManager^ ResMgr = gcnew System::Resources::ResourceManager("rjksClient.Shatou", GetType()->Assembly);
		PictureBox^ pb;
		//add faces
		for each (String^ s in res){
			if(!has_skip){//first one
				has_skip=true;
				continue;
			}
			int id=int::Parse(s->Substring(0,3));
			if(id>=0 &&id<FACE_COUNT){
				pb=gcnew PictureBox();
				pb->SizeMode=PictureBoxSizeMode::Zoom;
				Image^ img=cli::safe_cast<System::Drawing::Image^>(ResMgr->GetObject(String::Format("SHATOU_{0:000}",id)));
				pb->Image=img;
				pb->Height=30;
				if(img->Size.Width/img->Size.Height>1.5)
					pb->Width=60;
				else
					pb->Width=30;
				rtxtConversation->AddControl(pb);
				_AppendText2Conversation(s->Substring(3),color,bkcolor,font,false);
			}else
				_AppendText2Conversation("!#"+s,color,bkcolor,font,false);
		}
		_AppendText2Conversation("",color,bkcolor,font,true);//newline
		this->rtxtConversation_lock->Release();
}

void frmIM::_AppendText2Conversation(String^ input, Color color, Color bkcolor,System::Drawing::Font^ font,bool newline){
		int orilength=rtxtConversation->Text->Length;
		rtxtConversation->AppendText(input + (newline?"\r\n":""));
		int p1 = rtxtConversation->Text->IndexOf(input,orilength);
		int p2 = input->Length;
		rtxtConversation->ForeColor = Color::Chartreuse;
		rtxtConversation->Select(p1, p2);
		rtxtConversation->SelectionColor = color;
		rtxtConversation->SelectionBackColor=bkcolor;
		rtxtConversation->SelectionFont=font;
		rtxtConversation->Refresh();
		rtxtConversation->ScrollToCaret();
}

 System::Void frmIM::faceClickHdl(System::Object^  sender, System::EventArgs^  e) {
		rtxtSend->AppendText("!#"+((String^)((PictureBox^)sender)->Tag));
		 }

void frmIM::loadFaces(){
	System::Resources::ResourceManager^ ResMgr = gcnew System::Resources::ResourceManager("rjksClient.Shatou", GetType()->Assembly);
	PictureBox^ pb;
	int offset=0;
	for(int i=0;i<FACE_COUNT;i++){
		int line_idx=(i+offset)%25;
		int line_cnt=(i+offset)/25;
		pb=gcnew PictureBox();
		pb->SizeMode=PictureBoxSizeMode::Zoom;
		pb->Location=System::Drawing::Point(line_idx*32,line_cnt*32);
		Image^ img=cli::safe_cast<System::Drawing::Image^>(ResMgr->GetObject(String::Format("SHATOU_{0:000}",i)));
		pb->Image=img;
		pb->Height=30;
		if(img->Size.Width/img->Size.Height>1.5){
			pb->Width=60;
			offset+=1;
		}else
			pb->Width=30;
		pb->Click += gcnew System::EventHandler(this, &frmIM::faceClickHdl);
		pb->Tag=String::Format("{0:000}",i);
		panelFace->Controls->Add(pb);
	}
	Label^ lbl=gcnew Label();
	lbl->Text=L"点击添加表情  ©傻头";
	lbl->Font = (gcnew System::Drawing::Font(L"微软雅黑", 10.8F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, 
				static_cast<System::Byte>(134)));
	lbl->ForeColor = System::Drawing::Color::SlateGray;
	lbl->Location = System::Drawing::Point(600, 228);
	lbl->Size = System::Drawing::Size(200, 25);
	panelFace->Controls->Add(lbl);
}